# -*- coding: utf-8 -*-

import logging
import os
import sys
from logging.handlers import TimedRotatingFileHandler
sys.path.append(os.path.dirname(__file__))
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))

from util.MyIO import MyIO
import util.config as config
from util.HttpConnectionPool import HttpConnectionPool


class FCLogger():
    def __init__(self,name):
        self.io = MyIO()
        self.name = name
        self.logger = logging.getLogger(name)
        self.logger.setLevel(logging.INFO)
        # 定义日志输出格式
        fmt_str = '%(asctime)s[%(levelname)s][%(processName)s][%(threadName)s]:%(message)s'
        # 初始化
        logging.basicConfig()
        # 创建TimedRotatingFileHandler处理对象
        # 间隔12h创建新的名称为LockerLog.%Y%m%d_%H%M%S.log的文件，并一直占用LockerLog文件。
        file_name = os.path.join(self.io.GetLogPath(),name)
        fh = logging.handlers.TimedRotatingFileHandler(file_name, when='D', interval=1, backupCount=0)
        # 设置日志文件后缀，以当前时间作为日志文件后缀名。
        fh.suffix = "%Y%m%d_%H%M%S.log"

        # 设置日志输出级别和格式
        fh.setLevel(logging.INFO)
        formatter = logging.Formatter(fmt_str)
        fh.setFormatter(formatter)
        self.logger.addHandler(fh)
    def info(self, msg):
        self.logger.info(msg)

    def warning(self,msg):
        self.logger.warning(msg)
        self.write_to_server('WARN',msg)
    def error(self,msg):
        self.logger.error(msg)
        self.write_to_server("ERROR",msg)
    def write_to_server(self,level,msg):
        try:
            msg = ": "+ msg
            log_content = {"requestId":"",
                           "callModelCode":"model-idsp-transter-sorting",
                           "invokedModelCode":"",
                           "invokedModelMethod":"",
                           "callStep":"",
                           "srcIp":"",
                           "logLevel":level,
                           "message":msg}
            http_connection_pool.async_post(json=log_content,callback = self.async_post_handler)

        except:
            self.logger.error("write log to remote server fail")
    def async_post_handler(self,res):
        self.logger.info(res)

logger_dict={}
http_connection_pool = HttpConnectionPool(config.log_url,multi_thread = True)
def getLogger(name):

    if name not in logger_dict.keys():
        logger = FCLogger(name)
        logger_dict.update({name:logger})
        return logger
    else:
        return logger_dict[name]

healthLog = FCLogger('healthCheck.log')
postLog = FCLogger('post.log')
